# -*- coding: utf-8 -*-
# base.urls
# 

# Following few lines is an example urlmapping with an older interface.
"""
from werkzeug.routing import EndpointPrefix, Rule

def make_rules():
  return [
    EndpointPrefix('base/', [
      Rule('/', endpoint='index'),
    ]),
  ]

all_views = {
  'base/index': 'base.views.index',
}
"""

from google.appengine.ext import db
from kay.generics import crud
from kay.generics import only_owner_can_write
from kay.generics import (
  OP_LIST, OP_SHOW, OP_CREATE, OP_UPDATE, OP_DELETE
)
from kay.routing import (
  ViewGroup, Rule
)
from kay.utils import get_request


class DeckCRUDViewGroup(crud.CRUDViewGroup):
  model = 'base.models.Deck'
  form = 'base.forms.DeckForm'
  authorize = only_owner_can_write
  owner_attr = 'owner'
  templates = crud.CRUDViewGroup.templates.copy()
  templates[OP_SHOW] = 'base/deck_show.html'
  templates[OP_LIST] = 'base/deck_list.html'

  def get_query(self, request):
    return self.model.all().filter('owner =', request.user.key()).\
        order('-created')


class CardCRUDViewGroup(crud.CRUDViewGroup):
  model = 'base.models.Card'
  form = 'base.forms.CardForm'
  authorize = only_owner_can_write
  owner_attr = 'owner'
  templates = crud.CRUDViewGroup.templates.copy()
  templates[OP_LIST] = 'base/card_list.html'

  def _get_deck(self, request):
    # if deck is not found, just throw exception
    return db.get(request.args['deck'])

  def get_query(self, request):
    deck = self._get_deck(request)
    return self.model.all().filter('owner =', request.user.key()).\
        ancestor(deck.key()).order('-created')

  def get_additional_context_on_create(self, request, form):
    context = crud.CRUDViewGroup.get_additional_context_on_create(self, request,
        form)
    deck = self._get_deck(request)
    context['parent'] = deck
    return context

  def get_create_url(self):
    return self.url_for(self.get_endpoint(OP_CREATE),
        deck=get_request().args['deck'])

  def get_delete_url(self, obj):
    return self.url_for(self.get_endpoint(OP_DELETE), key=obj.key(),
        deck=get_request().args['deck'])

  def get_update_url(self, obj):
    return self.url_for(self.get_endpoint(OP_UPDATE), key=obj.key(),
        deck=get_request().args['deck'])

  def get_list_url(self, cursor=None):
    return self.url_for(self.get_endpoint(OP_LIST), cursor=cursor,
        deck=get_request().args['deck'])
  
view_groups = [
  ViewGroup(
    Rule('/', endpoint='list_deck', view='base.urls.DeckCRUDViewGroup.list'),
  ),
  DeckCRUDViewGroup(),
  CardCRUDViewGroup()
]

